package com.pmcc.miniProgram.web;


import com.google.gson.Gson;
import com.pmcc.miniProgram.vo.CodeExchangeOpenid;
import com.pmcc.platform.giftGoods.service.GoodsService;
import com.pmcc.platform.salesman.entity.Salesman;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.salesman.service.SalesmanService;
import com.pmcc.platform.shop.entity.ShopInfo;
import com.pmcc.platform.shop.service.ShopInfoService;
import com.pmcc.platform.shopping.entity.Shopping;
import com.pmcc.platform.shopping.service.ShoppingService;
import com.pmcc.platform.user.entity.MinSalesmanUserInfo;
import com.pmcc.platform.user.entity.MinShoppingUserInfo;
import com.pmcc.platform.user.entity.UserInfo;
import com.pmcc.platform.user.repository.MinSalesmanUserInfoRepository;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.platform.user.service.UserService;
import com.pmcc.utils.AntPage;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.StringUtil;
import com.pmcc.utils.UUIDGenerator;
import com.pmcc.utils.wechat.HttpClientUtil;
import com.pmcc.utils.wechat.WXBizDataCrypt;
import com.pmcc.utils.wechat.WechatMiniConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/miniProgram/salesman/")
public class MiniSalesmanController {

    @Autowired
    SalesmanService salesmanService;

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    MinSalesmanUserInfoRepository minSalesmanUserInfoRepository;

    @Autowired
    ShopInfoService shopInfoService;

    @Autowired
    UserService userService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ShoppingService shoppingService;

    /**
     * 用户生成code
     *
     * @return
     */
    public String createCode() {
        String userCode = UUIDGenerator.generateShortUuid();
        List<MinSalesmanUserInfo> code = minSalesmanUserInfoRepository.findAllByCode(userCode);
        if (code != null && code.size() > 0) {
            return createCode();
        } else {
            return userCode;
        }
    }

    /**
     * 授权用户个人信息
     * @param minSalesamnUserId
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    @RequestMapping(value = "saveUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean saveUserInfo(String minSalesamnUserId, String sessionKey, String encryptedData, String iv) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(minSalesamnUserId) || StringUtil.isEmpty(encryptedData) || StringUtil.isEmpty(sessionKey) || StringUtil.isEmpty(iv)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("请求失败！minSalesamnUserId为空！");
            return apiResultBean;
        }

        WXBizDataCrypt biz = new WXBizDataCrypt(WechatMiniConfig.SALESAMAN_MINI_APP_ID, sessionKey);
        String returnInfo = biz.decryptData(encryptedData, iv);
        JSONObject object = JSONObject.fromObject(returnInfo);
        String userinfo = object.get("userInfo").toString();
        JSONObject jsonObject = JSONObject.fromObject(userinfo);

        //获取公共配置
        //如果没有unionId，就用openId查询

        MinSalesmanUserInfo minSalesmanUserInfo=minSalesmanUserInfoRepository.findAllById(minSalesamnUserId);


        if (jsonObject.get("nickName") != null) {
            String aa = this.filterEmoji(jsonObject.get("nickName").toString(), "");
            minSalesmanUserInfo.setNickName(aa);
        }
        if (jsonObject.get("avatarUrl") != null) {
            minSalesmanUserInfo.setPhotoUrl(jsonObject.get("avatarUrl").toString());
        }
        if (jsonObject.get("gender") != null) {
            minSalesmanUserInfo.setSex(jsonObject.get("gender").toString());
        }
        if (jsonObject.get("phoneNumber") != null) {
            minSalesmanUserInfo.setPhone(jsonObject.get("phoneNumber").toString());
            //如果保存手机号，并且推荐人信息不为空，增加推荐记录
        }
        //处理最后浏览店铺

        minSalesmanUserInfo.setModifyTime(new Date());
        minSalesmanUserInfoRepository.saveAndFlush(minSalesmanUserInfo);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("获取成功");
        apiResultBean.setData(minSalesmanUserInfo);
        return  apiResultBean;
    }


    /**
     * emoji表情替换
     *
     * @param source
     * @param slipStr
     * @return
     */
    private String filterEmoji(String source, String slipStr) {
        if (StringUtils.isNotBlank(source)) {
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", slipStr);
        } else {
            return source;
        }
    }

    /**
     * 登录凭证校验(微信小程序)
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenid", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean getOpenid(String code) {
        ApiResultBean apiResultBean = new ApiResultBean();
        //根据code换取对应的openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WechatMiniConfig.SALESAMAN_MINI_APP_ID + "&secret=" + WechatMiniConfig.SALESAMAN_MINI_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        // String tokenUrl
        String jsonStr = HttpClientUtil.httpGetRequest(url);

        Gson gson = new Gson();

        CodeExchangeOpenid codeExchangeOpenid = gson.fromJson(jsonStr, CodeExchangeOpenid.class);


        if (StringUtil.isEmpty(codeExchangeOpenid.getErrcode())) {
            List<MinSalesmanUserInfo> minSalsemanUserInfos = minSalesmanUserInfoRepository.findAllByOpenIdAndDelFlag(codeExchangeOpenid.getOpenid(), "0");
            //判断用户表是否有记录
            if (minSalsemanUserInfos.size() > 0) {
                //判断当前登录微信是否已经是业务员
                List<Salesman> salesmens = salesmanRepository.findAllByMinSalesmanUserIdAndDelFlag(minSalsemanUserInfos.get(0).getId(), "0");

                if (salesmens.size() > 0) {
                    minSalsemanUserInfos.get(0).setSalesmanId(salesmens.get(0).getId());
                    minSalsemanUserInfos.get(0).setIsLog("0");
                  //  minSalsemanUserInfos.get(0).setSessionKey(codeExchangeOpenid.getSession_key());
                    apiResultBean.setData(minSalsemanUserInfos.get(0));
                    apiResultBean.setMsg("获取成功");
                    return apiResultBean;
                    //没有则需要去往登陆页面进行手机验证
                } else {
                    minSalsemanUserInfos.get(0).setIsLog("1");
                    minSalsemanUserInfos.get(0).setSessionKey(codeExchangeOpenid.getSession_key());
                    apiResultBean.setData(minSalsemanUserInfos.get(0));
                    apiResultBean.setMsg("获取成功");
                    return apiResultBean;
                }

            } else {
                MinSalesmanUserInfo minSalsemanUserInfo = new MinSalesmanUserInfo();
                minSalsemanUserInfo.setIsLog("1");
                minSalsemanUserInfo.setSessionKey(codeExchangeOpenid.getSession_key());
                minSalsemanUserInfo.setOpenId(codeExchangeOpenid.getOpenid());
                minSalesmanUserInfoRepository.save(minSalsemanUserInfo);
                apiResultBean.setData(minSalsemanUserInfo);
                apiResultBean.setMsg("获取成功");
                return apiResultBean;

            }


        } else {
            //处理错误信息
            CodeExchangeOpenid.handleError(codeExchangeOpenid, apiResultBean);
            return apiResultBean;
        }



    }


    /**
     * 查看导购申请记录
     *
     * @param salesmanId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "queryShoppingApply", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryShoppingApply(String salesmanId, AntPage antPage) {
        return salesmanService.queryShoppingApply(salesmanId, antPage);
    }

    /**
     * 审核导购申请
     *
     * @param salesmanId
     * @return
     */
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean audit(String salesmanId, String shoppingAplyId) {
        return salesmanService.audit(salesmanId, shoppingAplyId);
    }

    /**
     * 店铺管理
     *
     * @param salesmanId
     * @param antPage
     * @param field
     * @return
     */
    @RequestMapping(value = "queryShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryShop(String salesmanId, AntPage antPage, String field) {
        return salesmanService.queryShop(salesmanId, antPage, field);
    }


    /**
     * 添加店铺
     *
     * @param shopInfo
     * @return
     */
    @RequestMapping(value = "/addShop", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean addShop(ShopInfo shopInfo) {
        return shopInfoService.salesamanAddShop(shopInfo);

    }

    /**
     * 用户列表
     * @param salesmanId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean userList(String salesmanId,AntPage antPage){
        return   userService.userList(salesmanId,antPage);
    }

    /**
     * 用户详情列表
     * @param salesmanId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDetails", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean userDetails(String salesmanId,String userId,AntPage antPage){
        return   userService.userDetails(salesmanId,userId,antPage);
    }

    /**
     * 选择门店
     * @param salesmanId
     * @param antPage
     * @param field
     * @return
     */
    @RequestMapping(value = "/selectShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean selectShop(String salesmanId,AntPage antPage,String field ){
    return  shopInfoService.selectShop(salesmanId,antPage,field);
    }

    /**
     * 赠品列表
     * @param salesmanId
     * @param antPage
     * @param goodsName
     * @return
     */
    @RequestMapping(value = "/goodsList", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean goodsList(String salesmanId,AntPage antPage,String goodsName){
        return  shopInfoService.goodsList(salesmanId,antPage,goodsName);
    }

    /**
     * 领取详情
     * @param salesmanId
     * @param goodsId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/getDetail", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean getDetail(String salesmanId,String goodsId,AntPage antPage){
        return  shopInfoService.getDetail(salesmanId,goodsId,antPage);
    }


    /**
     * 店铺导购列表
     * @param shopId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/shopsList", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean shopsList(String shopId,AntPage antPage){
        return  shopInfoService.shopsList(shopId,antPage);
    }

    /**
     * 店铺详情
     * @param shopId
     * @param startTime
     * @param endTime
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/shopDetail", method = RequestMethod.GET)
    @ResponseBody
    public  ApiResultBean shopDetail(String shopId,String startTime,String endTime,AntPage antPage){
        return  shopInfoService.shopDetail(shopId,startTime,endTime,antPage);
    }

    /**
     * 选择赠品
     * @param antPage
     * @param goodsName
     * @return
     */
    @RequestMapping(value = "/selectGoodsGift", method = RequestMethod.GET)
    @ResponseBody
    public  ApiResultBean selectGoodsGift(AntPage antPage,String goodsName){
            return  goodsService.selectGoodsGift(antPage,goodsName);
    }

    /**
     * 添加赠品
     * @param shopId
     * @param goodsId
     * @param num
     * @return
     */
    @RequestMapping(value = "/addGoodsGift", method = RequestMethod.GET)
    @ResponseBody
    public  ApiResultBean addGoodsGift(String shopId,String goodsId,int num,String salesmanId){
        return  shopInfoService.addGoodsGift(shopId,goodsId,num,salesmanId);
    }

    /**
     * 设置赠品数量
     * @param shopId
     * @param goodsId
     * @param num
     * @param state
     * @return
     */
    @RequestMapping(value = "/modifyGoodsGiftNum", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean modifyGoodsGiftNum(String shopId,String goodsId,int num,String state,String salesmanId){
        return  shopInfoService.modifyGoodsGiftNum(shopId,goodsId,num,state,salesmanId);
    }


    /**
     * 修改店铺信息
     * @param shopInfo
     * @return
     */
    @RequestMapping(value = "/salesmanModifyShop", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean salesmanModifyShop(ShopInfo shopInfo){
        return  shopInfoService.salesmanModifyShop(shopInfo);

    }

    /**
     * 门店导购接口
     * @param shopId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/querySalesmanIdAllShopping", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean querySalesmanIdAllShopping(String shopId,AntPage antPage){
        return  shopInfoService.querySalesmanIdAllShopping(shopId,antPage);
    }

    /**
     * 导购管理
     * @param salesmanId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/shoppingAdmin", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean shoppingAdmin(String salesmanId,AntPage antPage,String field){
        return  shoppingService.shoppingAdmin(salesmanId,antPage,field);
    }

    /**
     * 删除店铺
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/salesmanDeletShop", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean salesmanDeletShop(String shopId){
        return  shopInfoService.salesmaneletShop(shopId);
    }


    /**
     * 导购详情
     * @param shoppingId
     * @param startTime
     * @param endTime
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/shoppingDeatil", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean shoppingDeatil(String shoppingId,String startTime,String endTime,AntPage antPage,String shopId){
       return   shopInfoService.shoppingDeatil(shoppingId,startTime,endTime,antPage, shopId);

    }

    /**
     * 业务员添加导购
     * @param shopping
     * @return
     */
    @RequestMapping(value = "/salesamanAddShopping", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean salesamanAddShopping(Shopping shopping){
        return   shoppingService.salesamanAddShopping(shopping);
    }

    /**
     * 业务员修改店铺
     * @param salesmanId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/salesmanQueryShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean salesmanQueryShop(String salesmanId,AntPage antPage){
        return  salesmanService.salesmanQueryShop(salesmanId,antPage);
    }

    /**
     * 赠品详情
     * @param goodsId
     * @param shopId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/goodsGiftDetail", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean goodsGiftDetail(String goodsId,String shopId,AntPage antPage,String salesmanId){
        return  salesmanService.goodsGiftDetail(goodsId,shopId,antPage,salesmanId);

    }




}